/**
 * 页面控制器
 */

import HttpUtil from '../../lib/trilobite/core/httputil.js'

let app=getApp();
let addrselect;
let http;
let httpfindbyid;
let httpsave;
let httpdelete;
let select=0;
let provinces_data=[{}];
let city_data = [{}];
let district_data = [{}];
let town_data = [{}];
let isupdate=false;
let comp,self;
/**
 * 新增地区的控制器
 */
class PageController {
  constructor(){
    comp=this;
    http = new HttpUtil(app);
    http.addResultListener(this.selectAddrResult);
    httpsave = new HttpUtil(app);
    httpsave.addResultListener(this.saveResult);
    httpfindbyid = new HttpUtil(app);
    httpfindbyid.addResultListener(this.findByidResult);
    httpdelete = new HttpUtil(app);
    httpdelete.addResultListener(this.deleteResult);
  }

  deleteResult=(e)=>{
    if(e.data.code===200){
      wx.navigateBack();
    }
  }

  findByidResult=(res)=>{
    console.log(res.data.data);
    var pro = 'this.data.provinces.selProvince'
    addrselect.setData({
      addressData:res.data.data,
      selProvince: res.data.data.province,
      selCity: res.data.data.city,
      selDistrict: res.data.data.region,
      selTown: res.data.data.town
      // selProvince: res.data.data.province,
      // selProvinceIndex: 0,
      // selCity: res.data.data.city,
      // selCityIndex: 0,
      // selDistrict: res.data.data.region,
      // selDistrictIndex: 0,
      // selTown: res.data.data.town,
      // selTownIndex: 0
      });
      console.log(this.data)
    // provinces_data[0].localName = res.data.data.province
    // provinces_data[0].regionId = res.data.data.provinceId
    // city_data[0].localName = res.data.data.city
    // city_data[0].regionId = res.data.data.cityId
    // district_data[0].localName = res.data.data.region
    // district_data[0].regionId = res.data.data.regionId
    // town_data[0].localName = res.data.data.town
    // town_data[0].regionId = res.data.data.townId
  
  }

  saveResult=(res)=>{
    if(res.data.code===200){
      wx.showModal({
        title: '提示',
        content: '地址保存成功',
        showCancel: 'false'
      })
    }
    setTimeout(function(){
      wx.navigateBack({
        delta: 1,
      })
    },2000)
   
  }

  deleteAddress=(e)=>{
     wx.showModal({
       title: '提示',
       content: '你是否确认删除改地址',
       success(r){
           if(r.confirm){
             console.log(e);
             httpdelete.post("/EsMemberAddress/Delete", { id: e.currentTarget.dataset.id})
             //e.currentTarget.dataset.id
           }
       }
     })
  }

  data={
    selProvince: '请选择',
    selCity: '请选择',
    selDistrict: '请选择',
    selTown: '请选择',
    provinces: [],
    citys: [],
    districts: [],
    towns:[],
  }
  /**
   * 选择地区的结果
   */
  selectAddrResult=(res)=>{
    if (select===0){
      let arr=[];
      provinces_data=res.data.data;
      res.data.data.map((e) => {
         arr.push(e.localName)
      });
      addrselect.setData({ provinces: arr })
    }else if(select===1){
      let arr = [];
      city_data = res.data.data;
      res.data.data.map((e) => {
        arr.push(e.localName)
      });
      addrselect.setData({ citys: arr })
    }else if(select===2){
      
      let arr = [];
      district_data = res.data.data;
      res.data.data.map((e) => {
        arr.push(e.localName)
      });
      addrselect.setData({ districts: arr })
    }else if(select===3){
      let arr = [];
      town_data = res.data.data;
      res.data.data.map((e) => {
        arr.push(e.localName)
      });
      addrselect.setData({ towns: arr })
    }
  }

 onLoad=function(e){
   addrselect=this;
   self=this;
   //console.log(e.id);
   isupdate=false;
   if(e.id){
     httpfindbyid.post("/EsMemberAddress/FindById", { addrId: e.id });
     isupdate=true;
     addrselect.setData({addrId:e.id});
     //this.id=e.id;
     //addrselect.setData({display})
   }
 }

  /**
   * 当界面显示完成的时候，执行省的数据加载
   */
  onReady=function(){
    addrselect = this;
    this.setData({
      provinces: [],
      citys: [],
      districts: [],
    });
    select=0;
    http.post("/EsRegions/FindByParentId", { parentId: 0 });
  }
  valiSelect=()=>{
    self.setData({
      selProvince: '请选择',
      selProvinceIndex: 0,
      selCity: '请选择',
      selCityIndex: 0,
      selDistrict: '请选择',
      selDistrictIndex: 0,
      selTown: '请选择',
      selTownIndex: 0,
    })
    town_data=[];
    comp.showMessage("请以先后顺序选择");
    select=0;
  }
  /**
   * 执行省数据选中，并执行州的数据触发
   */
  bindPickerProvinceChange=function(e){
    if(select!==0){
      comp.valiSelect();
      return;
    }
    this.setData({
      selProvince: provinces_data[e.detail.value].localName,
      selProvinceIndex: e.detail.value,
      selCity: '请选择',
      selCityIndex: 0,
      selDistrict: '请选择',
      selDistrictIndex: 0,
      selTown:'请选择',
      selTownIndex:0,
    })
    select=1;
    http.post("/EsRegions/FindByParentId", { parentId: provinces_data[e.detail.value].regionId });
  }


 /**
   * 执行州数据选中，并执行县的数据触发
   */
  bindPickerCityChange=function (e) {
    if (select !== 1) {
      comp.valiSelect();
      return;
    }
    this.setData({
      selCity: city_data[e.detail.value].localName ,
      selCityIndex: e.detail.value,
      selDistrict: '请选择',
      selDistrictIndex: 0,
      selTown: '请选择',
      selTownIndex: 0,
    })
    select = 2;
    http.post("/EsRegions/FindByParentId", { parentId: city_data    [e.detail.value].regionId });
  }
 /**
   * 执行县数据选中，并执行镇的数据触发
   */
  bindPickerDistrictChange = function (e) {
    if (select !== 2) {
      comp.valiSelect();
      return;
    }
    this.setData({
      selDistrict: district_data[e.detail.value].localName,
      selDistrictIndex: e.detail.value,
      selTown: '请选择',
      selTownIndex: 0,
    })
    select = 3;
    http.post("/EsRegions/FindByParentId", { parentId: district_data[e.detail.value].regionId });
  }
  /**
   * 执行镇数据选中，结束选择
   */
  bindPickerTownChange= function (e) {
    if (select !== 3) {
      comp.valiSelect();
      return;
    }
    if (town_data[e.detail.value]){
      this.setData({
        selTown: town_data[e.detail.value].localName,
        selTownIndex: e.detail.value,
      })
    }
    
  }

  showMessage=(m)=>{
    wx.showModal({
      title: '提示',
      content: m,
      showCancel:false
    })
  }
  /**
   * 保存地址
   */
  save=(e)=>{
    //console.log(provinces_data, addrselect.data.selProvince);

    if (!provinces_data[addrselect.data.selProvinceIndex]) {
      this.showMessage("地区不能为空！")
      return;
    }
    let addr = { 
      memberId: app.globalData.userInfo.memberId,
      ...e.detail.value,
      province: provinces_data[addrselect.data.selProvinceIndex].localName,
      provinceId: provinces_data[addrselect.data.selProvinceIndex].regionId,
      city: city_data[addrselect.data.selCityIndex].localName,
      cityId: city_data[addrselect.data.selCityIndex].regionId,
      region: district_data[addrselect.data.selDistrictIndex].localName,
      regionId: district_data[addrselect.data.selDistrictIndex].regionId,
      };
    if (town_data[addrselect.data.selTownIndex]&&town_data[addrselect.data.selTownIndex].localName!==""){
        addr.town=town_data[addrselect.data.selTownIndex].localName;
        addr.townId= town_data[addrselect.data.selTownIndex].regionId;
      }else{
        addr.town=""
        addr.townId=0;
      }
    if ((!addr.province||addr.province==="")||(!addr.city||addr.city==="")||(!addr.region||addr.region==="")){
         this.showMessage("地区选择不完整")
         return;
       }

      if (!addr.name&&addr.name===""){
        this.showMessage("联系人不能为空！")
        return;
      }

    if (!addr.mobile && addr.mobile === "" || addr.mobile.length<11) {
        this.showMessage("手机号码填写有误")
        return;
      }
      if (!addr.addr && addr.addr === "") {
        this.showMessage("详细地址不能为空！")
        return;
      }
      if (!addr.zip && addr.zip === "") {
        this.showMessage("邮政编号不能为空！")
        return;
      }

      if (!isupdate){
        httpsave.post("/EsMemberAddress/Add", addr);
      }
      if (isupdate) {
        let addrupdate = { addrId: addrselect.data.addrId,...addr};
        httpsave.post("/EsMemberAddress/Update", addrupdate);
      }
     
  }
  /**
   * 取消按钮返回之前的页面
   */
  bindCancel= ()=> {
    wx.navigateBack({})
  }
}

Page(new PageController());
